package com.cwnu.sw.cys.core.common.event.listener;

import com.cwnu.sw.cys.core.common.event.UserOnlineEvent;
import com.cwnu.sw.cys.core.user.dao.UserDao;
import com.cwnu.sw.cys.core.user.domain.entity.User;
import com.cwnu.sw.cys.core.user.domain.enums.ChatActiveStatusEnum;
import com.cwnu.sw.cys.core.user.service.IpService;
import com.cwnu.sw.cys.core.user.service.UserBackpackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * 用户在线事件监听器
 *
 * @author jisam
 * @version 1.0
 * @contact "jisamchan@outlook.com"
 * @date 29/03/2025
 */
@Component
@Slf4j
public class UserOnlineEventListener {

    @Autowired
    private UserBackpackService userBackpackService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private IpService ipService;

    /**
     * 保存用户在线状态
     *
     * @param event 用户在线事件
     */
    @Async
    @TransactionalEventListener(classes = UserOnlineEvent.class, phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
    public void saveUser(UserOnlineEvent event) {
        User user = event.getUser();
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setActiveStatus(ChatActiveStatusEnum.ONLINE.getStatus());
        updateUser.setLastOptTime(user.getLastOptTime());
        updateUser.setIpInfo(user.getIpInfo());
        userDao.updateById(updateUser);
        // 更新IP信息
        ipService.refreshIpDetailAsync(user.getId());
    }
}
